#include "completion.h"
char* list_cmd[] = {"echo", "cd", "ls", "mkdir", "rm", "cp", "mv", "bg", "clr", "dir", "exec", "exit", "environ", "fg", "help", "jobs", "pwd", "quit", "set", "shift", "test", "time", "umask", "unset","history"};
char* list_ls[] = {"test/","-l"};
char** completion(const char* text, int start, int end) {
    char** matches = NULL;

      
    if (start == 0) {
          
        matches = rl_completion_matches(text, cmd_genera);
    } else {
          
        matches = rl_completion_matches(text, argument_genera);
    }

    return matches;
}

char* cmd_genera(const char* text, int state) {
    static int list_index, len;
    char* cmd;

    if (!state) {
        list_index = 0;
        len = strlen(text);
    }

    while ((cmd = list_cmd[list_index++])) {
        if (strncmp(cmd, text, len) == 0) {
            return strdup(cmd);
        }
    }

    return NULL;
}

char* argument_genera(const char* text, int state) {
    static int list_index, len;
    char* argument;

    if (!state) {
        list_index = 0;
        len = strlen(text);
    }

      
    const char* cmd = rl_line_buffer;
      
    if (strstr(cmd, "cd") != NULL) {
          
        if (list_index == 0) {
              
            char* cur_dir = getenv("PWD");
              
            DIR* dir = opendir(cur_dir);
            if (dir != NULL) {
                  
                struct dirent* entry;
                while ((entry = readdir(dir)) != NULL) {
                     
                    if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) {
                          
                        if (strncmp(entry->d_name, text, len) == 0) {
                            return strdup(entry->d_name);
                        }
                    }
                }
                  
                closedir(dir);
            }
        }
    } else if (strcmp(cmd, "echo") == 0) {
          
        if (list_index == 0) {
              
            extern char** environ;

            while (environ[list_index] != NULL) {
                  
                if (strncmp(environ[list_index], text, len) == 0) {
                    return strdup(environ[list_index]);
                }
                list_index++;
            }
        }
    }
    else if (strstr(cmd, "ls") != NULL)
    {
        char* cmd;
        while ((cmd = list_ls[list_index++])) {
            if (strncmp(cmd, text, len) == 0) {
                return strdup(cmd);
            }
        }
    }

    return NULL;
}

